import os
import glob
import logging
from fastapi import APIRouter, HTTPException
from app.core.config import settings

router = APIRouter()

@router.get("/check-product-paths")
async def check_product_paths():
    """
    检查产品目录结构，用于调试前端产品列表加载问题
    """
    try:
        result = {
            "config": {
                "products_dir": settings.PRODUCTS_DIR,
                "static_dir": settings.STATIC_DIR,
                "static_uploads_dir": os.path.join(settings.STATIC_DIR, "uploads"),
                "static_products_dir": os.path.join(settings.STATIC_DIR, "uploads", "products")
            },
            "directories_exist": {},
            "products_found": {},
            "static_products": []
        }
        
        # 检查目录是否存在
        for path_name, path in result["config"].items():
            result["directories_exist"][path_name] = os.path.exists(path)
            
        # 检查常规产品目录
        if os.path.exists(settings.PRODUCTS_DIR):
            products = os.listdir(settings.PRODUCTS_DIR)
            result["products_found"]["regular_products_count"] = len(products)
            result["products_found"]["regular_products"] = products[:10]  # 只返回前10个
        
        # 检查静态产品目录
        static_products_dir = os.path.join(settings.STATIC_DIR, "uploads", "products")
        if os.path.exists(static_products_dir):
            products = os.listdir(static_products_dir)
            result["products_found"]["static_products_count"] = len(products)
            result["products_found"]["static_products"] = products[:10]  # 只返回前10个
            
            # 获取静态产品详情
            for product_id in products[:10]:  # 只处理前10个
                folder_path = os.path.join(static_products_dir, product_id)
                if os.path.isdir(folder_path):
                    # 获取产品名称
                    product_name = product_id.split("_")[0] if "_" in product_id else product_id
                    
                    # 检查是否有分析结果
                    result_file = os.path.join(folder_path, "analysis_result.yaml")
                    has_analysis = os.path.exists(result_file)
                    
                    # 获取图片数量
                    image_count = len(glob.glob(os.path.join(folder_path, "*.jpg"))) + \
                                len(glob.glob(os.path.join(folder_path, "*.jpeg"))) + \
                                len(glob.glob(os.path.join(folder_path, "*.png")))
                    
                    result["static_products"].append({
                        "id": product_id,
                        "name": product_name,
                        "has_analysis": has_analysis,
                        "image_count": image_count,
                        "folder_exists": os.path.exists(folder_path),
                        "is_directory": os.path.isdir(folder_path),
                        "folder_path": folder_path.replace("\\", "/"),
                        "files": os.listdir(folder_path)[:5] if os.path.isdir(folder_path) else []
                    })
                    
        return result
    except Exception as e:
        logging.error(f"检查产品路径时出错: {str(e)}")
        raise HTTPException(status_code=500, detail=f"检查产品路径失败: {str(e)}") 